class InvitationRequestsController < ApplicationController
	before_filter :registration_is_open, :except => :index
	before_filter :authorize_admin, :only => :index

	def index
		@created_invitation_requests = InvitationRequest.created
	end
	
	def create
		@person = Person.new(params[:person])
		@invitation_request = InvitationRequest.new(params[:invitation_request])
		
		previous_invitation_request = InvitationRequest.for @person.email_address

		if previous_invitation_request
			flash[:error] = invitation_request_already_created

			Mailer.deliver_invitation_request_status(previous_invitation_request)
			render :action => 'new'
			return
		end

		@invitation_request.change_status :created, "In process"

		@invitation_request.person = @person
		
		if !@invitation_request.valid? | !@person.valid?
			render :action => 'new'
			return
		end

		InvitationRequest.transaction do
			@invitation_request.save!
		end		

		flash[:notice] = thanks_for_requesting_an_invitation
		
		Mailer.deliver_invitation_request_confirmation(@invitation_request)
		Mailer.deliver_invitation_request_organizer_notification(@invitation_request)
		
		redirect_to root_path
	end
	
	protected
	def registration_is_open
		if not $registration_is_open
			flash[:notice] = 'Registration is not yet open. Please check back soon!'
			redirect_to root_path
		end
	end
	
	def invitation_request_already_created
		message = "An invitation request has already been created for #{ERB::Util.h @person.email_address}."
		message += "<br />"
		message += "<br />"
		message += "Cannot create another request."
		message += "<br />"
		message += "<br />"
		message += "A notification of this request has been sent to #{ERB::Util.h @person.email_address}."
		
		message
	end
	
	def thanks_for_requesting_an_invitation
		message = "Thanks for requesting an invitation to the #{ERB::Util.h EVENT_NAME}."
		message += "<br />"
		message += "<br />"
		message += "Requests for invitations to the conference will be processed within a few days."
		message += "<br />"
		message += "<br />"
		message += "A confirmation email has been sent to #{ERB::Util.h @person.email_address}."
		
		message
	end
end